import { GetCityPicker } from "@/api/common";
import { reactive } from "@vue/composition-api";

export function cityPicker() {
  const data = reactive({
    // 省份
    province: "",
    provinceData: [],
    // 城市
    city: "",
    cityData: [],
    // 区、县
    area: "",
    areaData: "",
    // 街道
    street: "",
    streetData: []
  });
  // 选中的值
  const resultData = reactive({
    province: "",
    city: "",
    area: "",
    street: ""
  });

  // 请求数据
  const getData = (params) => {
    GetCityPicker(params).then(res => {
      data[`${params.type}Data`] = res.data.data.data;
    }).catch(error => {
      console.log(error);
    });
  };

  // 获取省份
  const getProvince = () => {
    getData({ type: "province" });
  };

  // 选择省份， 获取城市
  const handlerProvince = (val) => {
    // 重置
    reset({ type: "city" });

    getData({ type: "city", province_code: val });

  };

  // 选择城市， 获取区、县
  const handlerCity = (val) => {
    // 重置
    reset({ type: "area" });

    getData({ type: "area", city_code: val });

  };

  // 选择区、县， 获取街道
  const handlerArea = (val) => {
    // 重置
    reset({ type: "street" });

    getData({ type: "street", area_code: val });

  };

  // 选择街道
  const handlerStreet = () => {
    result();
  };

  // 重置
  const reset = (params) => {
    let valJson = {
      city: ["city", "area", "street"],
      area: ["area", "street"],
      street: ["street"]
    };
    const arrObj = valJson[params.type];
    // 清除指定的key值
    if (arrObj) {
      arrObj.forEach(item => data[item] = "");
    }

    result();
  };

  // 返回数据集合
  const result = () => {
    for (let key in resultData) {
      resultData[key] = data[key];
    }
  };

  return {
    // toRefs 把对象数据类型转为基础数据类型，可进行解构响应
    // ...toRefs(data),
    data,
    resultData,
    getProvince,
    handlerProvince,
    handlerCity,
    handlerArea,
    handlerStreet
  };
}
